<template>
    <div>
        <ul>
            <li v-bind="$attrs" @click="chosePage(item)" v-for="(item, index) in arr" :class="pages.pageIndex === item ? 'active' : ''" :key="index">{{item}}</li>
        </ul>
    </div>
</template>

<script>
import { computed, reactive } from 'vue'
export default {
    props: {
        total: { // 数据的总数量
            type: Number,
            default: 101
        },

        pageSize: { // 每页显示多少条数据
            type: Number,
            default: 10,
        },

        pageIndex: { // 表示当前为第几页
            type: Number,
            default: 1
        }
    },
    setup(props, {emit}) {
        let pages = reactive({
            total: props.total,
            pageSize: props.pageSize,
            pageIndex: props.pageIndex
        })
        let arr = computed(() => {
            // 计算出一共多少页
            let all = Math.ceil(pages.total / pages.pageSize)
            if(all > 7) {
                if(pages.pageIndex <= 4) {
                    return [1, 2, 3, 4, 5, '...', all]
                } else if(pages.pageIndex >= all - 3) {
                    return [1, '...', all - 4, all-3, all-2, all -1, all]
                } else {
                    return [1, '...', pages.pageIndex - 2, pages.pageIndex - 1, pages.pageIndex,pages.pageIndex + 1, pages.pageIndex + 2, '...', all]
                }
            } else {
                let  small = []
                for(let i = 1; i<= all; i++) {
                    small.push(i)
                    
                }
                return small
            }

        })

        // 定义选择页码的函数
        let chosePage = (item) => {
            if(item == '...') {
                return
            } else {
                pages.pageIndex = item
            }
            emit('getIndex', item)
        }

        return {
            arr,
            chosePage,
            pages
        }
    },


    // methods: {
    //     chosePage(item) {
    //         this.$emit('getIndex', item)
    //     }
    // }
}
</script>

<style scoped>
ul {
    list-style: none;
    padding: 0;
    margin: 0;
    display: flex;
}
ul li {
    width: 20px;
    height: 20px;
    border: 1px solid #ccc;
    text-align: center;
    line-height: 20px;
    margin: 0 5px;
}
ul .active {
    background-color: skyblue;
    color: #fff;
}
</style>